<?php
/**
 * @copyright   Copyright(c) 2018
 * @author      tianjie
 * @link        http://www.tinphp.com/
 */

//公共函数文件

function returnJson($code, $msg = 'ok', $data = [])
{
    $json = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
    json($json);
}

//对指定下标的元素二维数组进行将维 输出一维数组
function ary_getwhere_out($field, $arr = array())
{
    $tmp = array();
    //把二维数组降维
    foreach ($arr as $key => $value) {
        $tmp[$key] = $value[$field];
    }

    return $tmp;
}

//将字符串分割成一维数组
//例:str_explode(',',$str);
function str_explode($epx, $string)
{
    $ary = array();
    $ary = explode($epx, $string);
    return $ary;
}

//将一维数组转换为字符串
//例:ary_to_str(',',$ary);
function ary_to_str($epx, $ary = array())
{
    $str = implode($epx, $ary);
    return $str;
}

/**
 * 字符串截取
 * @param string $str
 * @param int $start
 * @param int $num
 * @return string
 */
function substr_num(string $str, int $start, int $num): string
{
    $hz = (mb_strlen($str) > $num) ? '...' : '';
    return mb_substr($str, $start, $num) . $hz;
}

//时间戳转换为时间 输出格式为 Y-m-d
function rtdate($val)
{
    if ($val == "" || $val == 0) {
        $strtime = "";
    } else {
        $strtime = date("Y-m-d", $val);
    }
    return $strtime;
}

//时间戳转换为时间 输出格式为 Y-m-d H:i:s
function rttime($field)
{
    if ($field == "" || $field == 0) {
        $strtime = "";
    } else {
        $strtime = date("Y-m-d H:i:s", $field);
    }
    return $strtime;
}

//将年 月 日时间转化为时间戳
function timestamp($val)
{
    return strtotime($val);
}

//距今 天
function toDates($time_stamp)
{
    $time = time() - $time_stamp;
    $day = 24 * 60 * 60;
    return round($time / $day, 1);
}

//随机数0~9
//例：randomkeys(4) 生成四位随机数字
function randomkeys($length)
{
    $key = "";
    for ($i = 0; $i < $length; $i++) {
        $key .= mt_rand(0, 9);
    }
    return $key;
}

/**
 * mysql文件内容
 * @param string $FilePath 存储路径
 * @param int $Order 排序：0升序，1倒序
 * @return array 文件列表数组
 */
function myScandir(string $FilePath = './', int $Order = 0): array
{
    $FilePath = opendir($FilePath);
    while (false !== ($filename = readdir($FilePath))) {
        $FileAndFolderAyy[] = $filename;
    }
    $Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
    return $FileAndFolderAyy;
}

/**
 * 境界/修为计算
 * @param int $ulv 等级
 * @param int $identity 身份(等级大于等于120才生效) 0仙 1魔
 * @return array
 */
function state_hone(int $ulv, int $identity = 0)
{
    $str = '';
    $umaxexp = 100;
    $exp_diff = 4;  //异数(升到下一级所需修为倍数值)
    $honeStatus = 0; //面临突破的类型：0小境界突破，1大境界突破
    $data = [
        'grade' => [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
        'exp' => [1, 10, 20, 30, 40, 50, 70, 90, 110, 140, 170, 200],
        'mortal' => ['练气', '筑基', '金丹', '元婴', '化神', '炼虚', '合体', '大乘', ['散仙', '散魔'], ['天仙', '天魔'], ['金仙', '魔王'], ['仙帝', '魔帝']],
        'level' => ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
        'stage' => ['前期', '中期', '后期', '圆满'],
        'calledName' => ['尊者'],
    ];

    $num = count($data['grade']) - 1;
    if ($ulv >= $data['grade'][$num]) {
        $str = $data['calledName'][0];
        $umaxexp = $umaxexp * 100000000;
    } else {
        for ($i = 0; $i < count($data['grade']); $i++) {
            if ($ulv >= $data['grade'][$i] && $ulv < $data['grade'][$i + 1]) {
                $djc = $ulv - $data['grade'][$i];
                $jds = ceil(($data['grade'][$i + 1] - $data['grade'][$i]) / 10);    //几级=阶(层)

                $jieduan = floor($djc / $jds);

                if ($ulv < $data['grade'][8]) {
                    if ($jieduan == 9) {//大境界突破
                        $honeStatus = 1;
                    } else {//小境界突破
                        $honeStatus = 0;
                    }

                    $str = $data['mortal'][$i] . '期 ' . $data['level'][$jieduan] . '层';
                } else {
                    $stage = floor($jieduan / 3);
                    if ($stage == 3) {//大境界突破
                        $honeStatus = 1;
                    } else {//小境界突破
                        $honeStatus = 0;
                    }

                    $str = $data['mortal'][$i][$identity] . ' ' . $data['stage'][$stage];
                }

                $lv = $ulv + 1;
                $multiple = $data['exp'][$i] * 10;    //倍数
                $coefficient = $data['exp'][$i] * 40 + $umaxexp;    //系数
                $umaxexp = $exp_diff * $ulv * ($lv + round($lv / 2)) * $multiple + $coefficient;
                break;
            }
        }
    }

    return ['name' => $str, 'exp' => $umaxexp, 'honeStatus' => $honeStatus];
}

/**
 * 经典的概率算法
 * @param array $proArr 例：[1=>1,2=>10,3=>39,4=>50] ，二维数组请先用  array_column($ary, 'gl','id') 处理
 * @return int|string
 */
function get_rand(array $proArr)
{
    $result = '';
    //概率数组的总概率精度
    $proSum = array_sum($proArr);
    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);       //抽取随机数
        if ($randNum <= $proCur) {
            $result = $key;             //得出结果
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset ($proArr);
    return $result;
}

/**
 * 强化成功率
 * @param int $lv 当前装备强化等级
 * @return int 返回强化成功了
 */
function get_strengthen(int $lv = 0)
{
    if ($lv > 9) {
        if ($lv == 10) {
            $rate = 5;
        } else {
            $rate = 1;
        }
    } else {
        $rate = (100 - $lv * 10);
        /*
         * 0-1:100%
         * 1-2:90%
         * 2-3:80%
         * 3-4:70%
         * ...
         * 8-9:20%
         * 9-10:10%
         */
    }
    return round($rate);
}

/**
 * 装备强化是否成功
 * @param int $lv 当前装备强化等级
 * @return int 1成功 0失败
 */
function get_strengthen_status(int $lv)
{
    $randNum = mt_rand(1, 100);       //抽取随机数
    if ($randNum <= get_strengthen($lv)) {//成功
        return true;
    } else {//失败
        return false;
    }
}

/**
 * 强化所需材料数量
 * @param int $lv 当前装备强化等级
 * @param int $equip 当前装备等级
 * @return float
 */
function get_strengthen_stuff(int $lv, int $equip)
{
    if ($equip == 0) {
        $stuff = round($lv * $lv * 2 + 1);
    } else {
        $stuff = round($lv * $equip * 2 + $equip);
    }
    return $stuff;
}

/**
 * 更具当前装备强化等级获取属性提升的波动值
 * @param int $lv 当前装备强化等级
 */
function get_wave(int $lv)
{
    $wave = 10;
    $rate = 120 - get_strengthen($lv);
    if ($lv >= 15) {
        $wave = mt_rand(150, 200);
    }
    if ($lv < 15 && $lv >= 10) {
        $wave = mt_rand(100, 150);
    }
    if ($lv < 10 && $lv > 5) {
        $wave = mt_rand(50, $rate);
    }
    if ($lv <= 5) {
        $wave = mt_rand(10, $rate);
    }

    $wave = $wave / 100;
    return round($wave, 2);
}

/**
 * 装备强化平均波动值
 * @param int $lv 当前装备强化等级
 * @param int $num 均值次数 默认 10
 * @return float
 */
function get_average_wave(int $lv, int $num = 10)
{
    $num = ($num < 10) ? 10 : $num;
    $ary = [];
    for ($i = 0; $i < $num; $i++) {
        $wave = get_wave($lv);
        $ary[] = $wave;
    }
    sort($ary);
    unset($ary[0]);
    unset($ary[$num - 1]);
    return round(array_sum($ary) / ($num - 2), 2);
}

/**
 * 一对一 速度 随机补偿(增加速度低的一方先手几率)
 * @param $a int 速度
 * @param $b int 速度
 * @return int 补偿值
 */
function get_speed_compensate($a, $b)
{
    $diff = abs($a - $b);
    $diff = round($diff / 5) + 1;
    $diff = $diff * 5;
    return mt_rand(1, $diff);
}

/**
 * 计算暴击伤害
 * @param int $gj 攻击
 * @param int $bj 暴击
 * @return false|float
 */
function burst(int $gj, int $bj)
{
    $bj = ($gj == 0) ? 0 : $bj;
    $bj = round($bj * 1000);
    $bj = mt_rand(ceil($bj / 2), $bj);
    $bl = mt_rand(1, 9);
    return ceil((($gj * $bj) / 10000) * ($bl / 10));
}

/**
 * base64 加密
 * @param $data
 * @param string $key
 * @return string
 */
function str_base64_encode($data, $key = '')
{
    $key = ($key != '') ? '|' . $key : '';
    return base64_encode(urlencode($data) . $key) . createRandomStr(4);;
}

/**
 * base64 解密
 * @param $data
 * @return false|string
 */
function str_base64_decode($data)
{
    return base64_decode($data);
}

function createRandomStr($length)
{
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
    $strlen = 62;
    while ($length > $strlen) {
        $str .= $str;
        $strlen += 62;
    }
    $str = str_shuffle($str);
    return substr($str, 0, $length);
}

/**
 * 判断数字是否为大于等于零的整数
 * @param $int
 * @return false|int
 */
function gt0($int)
{
    $int = (integer)$int;
    if (preg_match("/^[1-9]\d*$/", $int)) {
        return $int;
    } else {
        return false;
    }
}